import type { ProColumns } from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import React, { useEffect, useState } from 'react';
import {
  invokeInterfaceInfoGetUsingGet,
  updateInterfaceInfoUsingPost
} from "@/services/api-share-backhend/interfaceInfoController";


type DataSourceType = {
  id: number;
  requestParams?: string;
  // paramType?:string;
  paramValue?: string;
};

export type proType = {
  id:number;
  requestParams: string;
  updateShow:(data:string)=>void;
  invokeBtnDisable:boolean
};

const GetDebugTable: React.FC<proType> = (props) => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();
  const [dataSource, setDataSource] = useState<DataSourceType[]>();
  const [tableKey, setTableKey] = useState(Date.now());
  const [invokeBtnDisable, setInvokeBtnDisable] = useState(()=>(false));

  const resetData=()=>{
    const params = props?.requestParams;
    if (params !== undefined&&params!==null) {
      try {
        const defaultParams = JSON.parse(params);
        const dataItems: DataSourceType[] = defaultParams.map((item, index) => {
          return {
            id: index,
            requestParams: item.param,
            paramValue: '',
          };
        });
        setDataSource(dataItems);
        setTableKey(Date.now());//强制刷新
        setInvokeBtnDisable(props.invokeBtnDisable)
      }
      catch (e){
        setDataSource(null);
        setInvokeBtnDisable(true)
        updateInterfaceInfoUsingPost({
          id:props.id,
          status:0})
        message.error("此接口参数异常，已设置为关闭状态，暂不可用！")

      }
    } else {
      message.info('注意此接口无需传参');
    }
  }
  //post
  const invokeTest=async ()=>{
    try {

      // console.log(dataSource)
      /*
0:
{id: 0, requestParams: 'name', paramValue: 'af'}
1:
{id: 1, requestParams: 'note', paramValue: 'dfasdfasd'}*/

      const result = dataSource?.reduce((acc, item) => {
        acc[item.requestParams] = item.paramValue;
        return acc;
      }, {});
      const res=await invokeInterfaceInfoGetUsingGet({
        id:props.id,
        // age?: ;
        // name?: ;
        ...result
      })
      if(res?.data){
        // resetData()
        props.updateShow(res?.data)

      }
      else{
        props.updateShow("");
        message.error(res.message)
      }
    }
    catch (e){
      message.error(e.message)
    }
  }

  useEffect(() => {
    resetData()
  }, []);

  useEffect(() => {
    if(dataSource!==undefined&&dataSource!==null) {
      setEditableRowKeys(() => dataSource.map((item) => item.id))
    }
  }, [dataSource,]);

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '参数名',
      dataIndex: 'requestParams',
      width: 60,
    },
    {
      title: '参数值',
      dataIndex: 'paramValue',
      width:100,
      // editable: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 20,
      render: () => {
        return null;
      },
    },
  ];
  return (
    <EditableProTable<DataSourceType>
        key={tableKey}
        headerTitle="请求参数"
      columns={columns}
      rowKey="id"
      value={dataSource}
      onChange={setDataSource}
      recordCreatorProps={{
          newRecordType: 'dataSource',
          record: () => ({
            id: Date.now(),
          }),
        }}
      toolBarRender={() => {
        return [
          <Button
            type="primary"
            key="save"
            disabled={invokeBtnDisable}
            onClick={() => {
                invokeTest()
            }}
          >
            调试
          </Button>,
        ];
      }}
      editable={{
        type: 'multiple',
        editableKeys,
        actionRender: (row, config, defaultDoms) => {
          return [defaultDoms.delete];
        },
        onValuesChange: (record, recordList) => {
          setDataSource(recordList);
        },
        onChange: setEditableRowKeys,
      }}
    />
  );
};
export default GetDebugTable;
